package com.zwz.service.impl;

import com.zwz.dto.RestrictionDTO;
import com.zwz.entity.ConsumptionRestriction;
import com.zwz.entity.EnterpriseInfo;
import com.zwz.entity.RiskInfoMain;
import com.zwz.mapper.ConsumptionRestrictionMapper;
import com.zwz.mapper.RiskInfoMainMapper;
import com.zwz.service.ConsumptionRestrictionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class ConsumptionRestrictionServiceImpl implements ConsumptionRestrictionService {

    @Autowired
    private RiskInfoMainMapper mainMapper;

    @Autowired
    private ConsumptionRestrictionMapper restrictionMapper;

    @Override
    public RestrictionDTO createWithMain(String enterpriseId  ) {
        // 主表操作
        // 1. 创建主表记录
        // 主表操作
        EnterpriseInfo enterpriseInfo=new EnterpriseInfo();
        enterpriseInfo.setId(Long.valueOf(enterpriseId));

        // 子表操作
        ConsumptionRestriction restriction = new ConsumptionRestriction();
        int k=0;
        restriction.setId(k++);
      restriction.setCurrentRestriction(false);
      restriction.setCurrentRestriction(false);

        validateRestriction(restriction);

        //最后关联上
        restriction.setEnterpriseId(Math.toIntExact(enterpriseInfo.getId()));

        restrictionMapper.insert(restriction);

        return new RestrictionDTO(enterpriseInfo, restriction);
    }

    @Override
    public void updateRestriction(ConsumptionRestriction restriction) {

    }

    @Override
    public List<ConsumptionRestriction> getCurrentRestrictions() {
        return null;
    }

    @Override
    public List<ConsumptionRestriction> getByCaseNumber(String caseNumber) {
        return null;
    }

    private void validateRestriction(ConsumptionRestriction restriction) {
        if (Boolean.TRUE.equals(restriction.getHasRestriction())) {
            if (restriction.getPublishDate() == null) {
                throw new IllegalArgumentException("存在消费限制必须包含发布日期");
            }
            if (StringUtils.isBlank(restriction.getCaseNumber())) {
                throw new IllegalArgumentException("案号不能为空");
            }
        }

        if (restriction.getEnforcementCount() != null && restriction.getEnforcementCount() < 0) {
            throw new IllegalArgumentException("执行数量不能为负数");
        }

        if (restriction.getEnforcementAmount() != null &&
                restriction.getEnforcementAmount().compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("涉案金额不能为负数");
        }
    }
}